extends PropertySetter


class_name ExpressionSetter


## 修改数据的操作表达式
@export_multiline var expression: String = ""
## 需要修改的数据对象
@export var character: ICharacterComponent = null


var __regex: RegEx = RegEx.new()


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "character": IComponent.find_up.bind(self, func(x): return x is ICharacterComponent, character)
    }, super.__check_exports())

func __prepare() -> void:
    super.__prepare()
    __regex.compile("[{\\$](.*?)[}]")

func __get_update_value(w: Object, p: String) -> Variant:
    var expression_result: String = expression
    var names: Array = []
    var values: Array = []
    for r in __regex.search_all(expression):
        var word: String = r.get_string()
        var key: String = word.substr(2, word.length() - 3)
        var cmpt: Node = character.subassembly(key)
        if cmpt == null:
            push_error("${" + key + "} is not in CharacterComponent")
            return null
        names.append(key)
        values.append(cmpt)
        expression_result = expression_result.replace(word, key)
    return NodeHelper.evaluate(self, expression_result, names, values)

func __get_wrapper_and_property() -> bool:
    var property_list: Array[String] = property.split('.')
    var target: Node = character
    if property_list.size() > 0 and __regex.search(property_list[0]):
        var cmpt_name: String = property_list[0].substr(2, property_list[0].length() - 3)
        var cmpt: Node = character.subassembly(cmpt_name)
        if cmpt == null:
            return false
        property_list.remove_at(0)
        target = cmpt
    var rlts: Array = NodeHelper.get_property_object(target, property_list)
    if rlts.size() < 1:
        push_error("'%s' is not in CharacterComponent" % property)
        return false
    cached_w = rlts[0]
    cached_p = rlts[1]
    return true
